package com.yunyao.web.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.yunyao.common.dto.InvoiceDto;
import com.yunyao.common.dto.InvoiceSourceDto;
import com.yunyao.common.dto.InvoiceSourceOrderDto;
import com.yunyao.common.dto.excel.ContractExcelDto;
import com.yunyao.common.dto.excel.InvoiceExcelDto;
import com.yunyao.common.dto.excel.SettlementExcelDto;
import com.yunyao.common.dto.project.ProjectDto;
import com.yunyao.common.web.util.PageResult;
import com.yunyao.common.web.util.YResult;
import com.yunyao.framework.dto.file.FileInfoDto;
import com.yunyao.framework.dto.invoice.InvoiceConfirmDto;
import com.yunyao.framework.dto.posyupply.PoSosyupplySaveDto;
import com.yunyao.framework.service.InvoiceService;
import com.yunyao.framework.service.SoInvoiceService;
import com.yunyao.framework.vo.Invoice.*;
import com.yunyao.framework.vo.project.ProjectSettlementVO;
import com.yunyao.framework.vo.projectorder.ProjectOrderVO;
import com.yunyao.framework.vo.reconciliation.ReconciliationOrderVO;
import com.yunyao.framework.vo.spreconciliation.SpReconciliationOrderVO;
import com.yunyao.framework.vo.supplier.SupplierSettlementVO;
import com.yunyao.web.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/invoice")
public class InvoiceController {
    @Autowired
    private InvoiceService invoiceService;
    @Autowired
    private SoInvoiceService soInvoiceService;
    /**
     * 获取供应商发票列表
     *
     * @param invoiceDto
     * @return
     */
    @GetMapping("/list")
    public YResult<PageResult<InvoiceVO>> getList(InvoiceDto invoiceDto) {
        return invoiceService.pageList(invoiceDto);
    }

    /**
     * 获取供应商发票详情信息
     *
     * @param id
     * @return
     */
    @GetMapping("/info")
    public YResult<InvoiceinfoVO> getInfo(Long id) {
        return invoiceService.getInvoiceById(id);
    }
    @GetMapping("/invoiceinfo")
    public YResult<InvoiceInfosssVO> getinvoiceInfo(Long id) {
        return invoiceService.getInvoicessssById(id);
    }
    @GetMapping("/sourceorder")
    public YResult<PageResult<InvoiceSourceOrderVO>> getSourceOrder(InvoiceSourceOrderDto invoiceId) {
        return invoiceService.getInvoiceSourceOrderById(invoiceId);
    }
    @GetMapping("/save/sourceorder")
    public YResult<PageResult<InvoiceSourceOrderVO>> getSourceOrder2(InvoiceSourceOrderDto invoiceId) {
        return invoiceService.getInvoiceSourceOrderBycontractId(invoiceId);
    }
    @GetMapping("/source")
    public YResult<PageResult<InvoiceSourceVO>> getSource(InvoiceSourceDto invoiceId) {
        return invoiceService.getInvoiceSourceById(invoiceId);
    }
    @GetMapping("/projectOrderlist")
    public YResult<PageResult<ProjectOrderVO>> getprojectOrderlist(InvoiceSourceDto invoiceId) {
        return invoiceService.getProjectOrderList(invoiceId);
    }

    @PostMapping("/delete")
    public YResult<Boolean> deleteInfo(@RequestBody InvoiceDto saveDto) {
        return invoiceService.deleteInfo(saveDto);
    }
    @GetMapping("/invoicelist")
    public YResult<PageResult<InvoiceVO>> getInvoiceList(InvoiceDto invoiceDto) {
        return invoiceService.pageInvoiceList(invoiceDto);
    }
    @PostMapping("/save/invoicelist")
    public YResult<String> saveBindID(@RequestBody InvoiceDto saveDto) {
        return soInvoiceService.saveBindId(saveDto);
    }
    @PostMapping("/saveproject")
    public YResult<String> saveproject(@RequestBody ProjectDto saveDto) {
        return soInvoiceService.saveProject(saveDto);
    }
    @GetMapping("/projectlist")
    public YResult<PageResult<SpReconciliationOrderVO>> getProjectList(InvoiceDto invoiceDto) {
        return invoiceService.pageProjectList(invoiceDto);
    }
    @GetMapping("/projectreconciliationorderlist")
    public YResult<PageResult<SpReconciliationOrderVO>> projectreconciliationorderlist(InvoiceDto invoiceDto) {
        return invoiceService.pageProjectList2(invoiceDto);
    }
    @PostMapping("/redinvoice")
    public YResult<String> redInoice(@RequestBody InvoiceDto saveDto) {
        return soInvoiceService.redInvoice(saveDto);
    }

    @PostMapping("/savestatus")
    public YResult<String> savestatus(@RequestBody InvoiceDto saveDto) {
        return soInvoiceService.saveStatus(saveDto);    }

    @PostMapping("/ycconfirm")
    public YResult<String> ycconfirm(@RequestBody @Validated InvoiceConfirmDto invoiceConfirmDto) {
        return soInvoiceService.ycconfirm(invoiceConfirmDto);
    }
    /**
     * 保存供应商发票信息
     *
     * @param saveDto
     * @return
     */
    @PostMapping("/save")
    public YResult<String> saveInfo(@RequestBody InvoiceDto saveDto) {
        return invoiceService.saveInfo(saveDto);
    }
    @GetMapping("/supplyreconciliationorderlist")
    public YResult<PageResult<ReconciliationOrderVO>> supplyreconciliationorderlist(InvoiceDto invoiceDto) {
        return soInvoiceService.pageProjectList3(invoiceDto);
    }
    @PostMapping("/makeout")
    public YResult<String> saveInvoice(@RequestBody InvoiceDto saveDto) {
        return soInvoiceService.saveInvoice(saveDto);
    }
    @GetMapping("/supplyreconciliationorderlist/count")
    public YResult<InvoiceCountVO> getcount(Long id) {
        return invoiceService.getcount(id);
    }


    /**
     * 导出文件
     *
     * @return
     */

    @GetMapping("/export/file")
    public YResult<String> exportFile(InvoiceDto invoiceDto, HttpServletResponse response) {
        try {
            List<InvoiceExcelDto> contractMaterialExportDtoList =  invoiceService.export(invoiceDto);
            try {
                // 这里URLEncoder.encode可以防止中文乱码
                String fileName = URLEncoder.encode("invoice", String.valueOf(StandardCharsets.UTF_8))+".xlsx";
//                response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
                //设置sheet名
                ExportParams params = new ExportParams();
                params.setSheetName("发票信息模版");
                //设置标题
//                params.setTitle("商品信息");
                // 这里需要设置不关闭流
                Workbook workbook = ExcelExportUtil.exportExcel(params, InvoiceExcelDto.class, contractMaterialExportDtoList);
                //输出流
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                workbook.write(bos);
                byte[] bytes = bos.toByteArray();
                bos.close();
                try {
                    FileInfoDto fileInfoDto = AliOssUtil.upload(bytes,
                            fileName, null);
                    if (null != fileInfoDto) {
                        return YResult.success(fileInfoDto.getLink());
                    } else {
                        return YResult.error("连接文件服务器失败，请重试");
                    }
                } catch (Exception e) {
                    return YResult.error("下载失败，请重试");
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }catch (Exception e) {
            log.error("导出发票信息失败",e);
        }
        return YResult.error("导出发票信息失败");
    }
}
